﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using System.Data;

namespace SharePointUsers
{
    static class Program
    {
   

        #region Private Members
        private static string ToolVersion = GetToolVersion();
        private static string Welcome = "********************************************\n" +
                                        "*    Welcome to the SP User Manager v{0}   *\n" +
                                        "*     Programmed by Ahmed Farag - 2013     *\n" +
                                        "********************************************\n";
        static string ArgsHelp = "\n\nTo use SP User Manager type the following:\n" +
                                      "-----------------------------------------\n\n" +
                                    "1- \"SPUManager.exe\" --> Starts the tool in windows\n" +
                                    "2- \"SPUManager.exe -Cmd\" --> Starts the tool in a command shell.\n\nUse the following parameters:\n\n" +
                                    "SPUManager.exe -Cmd \"-Report:<REPORT_DESIGN_FILE_LOCATION>\"\n"+
                                    "                    \"-SaveAs:<SAVE_AS_LOCATION_OF_REPORT_DATA>\"\n"+
                                    "                     [-NoPause] [-AppendDate]" +
                                    "\n\n" +
                                    "Parameters Guide:\n" +
                                    "-----------------\n\n"+
                                    "-Cmd        --> [Optional] Turn on the command line mode.\n" +
                                    "-Report     --> [Required] The location report design you want to execute.\n" +
                                    "-SaveAs     --> [Required] The location where you want to save the executed\n"+
                                    "                report data.\n" +
                                    "-NoPause    --> [Optional] Suppresses the pause at the end of executing\n"+
                                    "                the command line.\n" +
                                    "-AppendDate --> [Optional] Appends the date and time to the supplied file\n"+
                                    "                name in the '-SaveAs' param.\n" +
                                    "Examples:\n" +
                                    "--------\n\n"+
                                    "- C:\\> SPUManager.exe\n" +
                                    "- C:\\> SPUManager.exe -Cmd \"-Report:C:\\SharePoint Reports Designs\\SiteCollectionSize.rpt\""+
                                    "                            \"-SaveAs:C:\\ReportRuns\\SiteCollectionSize-2013-06-11.csv\"\n" +
                                    "- C:\\> SPUManager.exe -Cmd \"-Report:C:\\SharePoint Reports Designs\\SiteCollectionSize.rpt\""+
                                    "                            \"-SaveAs:C:\\ReportRuns\\SiteCollectionSize.csv\""+
                                    "                            -AppendDate -NoPause\n\n" +
                                    "Note:\n" +
                                    "-----\n\n"+
                                    "- This tool needs to run as administrator.\n";
        #endregion
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //Check if help needs to be displayed
            if (DoesArgumentExist("?", args) || 
                DoesArgumentExist("/?", args) ||
                DoesArgumentExist("/help", args) ||
                DoesArgumentExist("/GetHelp", args) ||
                DoesArgumentExist("-GetHelp", args))
            {
                AllocConsole();
                //Display welcome screen
                Console.WriteLine(Welcome, ToolVersion);
                Console.WriteLine(ArgsHelp);
                Console.WriteLine("Press any key to exit ...");
                Console.ReadKey();
                return;
            }

            //Check if running in command line mode
            if (!DoesArgumentExist("-cmd", args))
                WinModeMain(args);
            else
            {
                AllocConsole();
                ConsoleModeMain(args);
            }
        }
        static void WinModeMain(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        static void ConsoleModeMain(string[] args)
        {
            //Display welcome screen
            Console.WriteLine(Welcome, ToolVersion);
            if (ArgsAreValid(args))
            {
                //Prepare command control arg values 
                DateTime StartTime = DateTime.Now;
                bool SupressTerminationPause = DoesArgumentExist("-NoPause", args);
                bool AppendDateAndTime = DoesArgumentExist("-AppendDate", args);
                bool Verbose = DoesArgumentExist("-Verbose", args);

                //Prepare process control arg values

                string ReportPath = readStringArgumentValue("-report:",args);
                string ResultsPath = readStringArgumentValue("-saveas:", args);

                //Execute Process

                //Load the report design
                Report reportFile = null;
                try
                {
                    reportFile = Reporter.LoadReportObject(ReportPath);
                    SPUmanager.WriteSuccess("Report design loaded successfully ... ");
                }
                catch (Exception Ex)
                {
                    if (Verbose)
                        SPUmanager.WriteError("Error loading report design file.\nError details: {0}\nStack trace: {1}",
                        Ex.Message, Ex.StackTrace);
                    else
                        SPUmanager.WriteError("Error loading report design file.\nError details: {0}",
                        Ex.Message);
                }
                if (reportFile != null)
                {
                    //Execute the report
                    DataTable Results = null;
                    try
                    {
                        SPUmanager.WriteMessage("Executing report. Please wait, this may take serveral hours\\minutes depending on the report query ...");
                        Results = Reporter.ExecuteReport(reportFile, null);
                        SPUmanager.WriteSuccess("Report has been executed successfully ..");
                    }
                    catch (Exception Ex)
                    {
                        if (Verbose)
                            SPUmanager.WriteError("Error executing report.\nError details: {0}\nStack trace: {1}",
                            Ex.Message, Ex.StackTrace);
                        else
                            SPUmanager.WriteError("Error executing report.\nError details: {0}",
                            Ex.Message);
                    }

                    if (Results != null)
                    {
                        //Save the report to file
                        try
                        {
                            string FileName = "";
                            if (AppendDateAndTime)
                            {
                                string CurrentDateTime = StartTime.ToString("MM_dd_yy-HH_mm_ss");
                                FileName = AppendStringToFileName(ResultsPath, CurrentDateTime);
                            }
                            SPUmanager.WriteDataTableToFile(FileName, Results);
                            SPUmanager.WriteSuccess("The report has been saved to file successfully...");
                        }
                        catch (Exception Ex)
                        {
                            if (Verbose)
                                SPUmanager.WriteError("Error writing the report data to disk.\nError details: {0}\nStack trace: {1}",
                                Ex.Message, Ex.StackTrace);
                            else
                                SPUmanager.WriteError("Error writing the report data to disk.\nError details: {0}",
                                Ex.Message);
                        }
                    }
                }
                
                if (!SupressTerminationPause)
                {
                    Console.WriteLine("Press any key to exit ...");
                    Console.ReadKey();
                }
            }
            else
            {
                Console.WriteLine("Press any key to exit ...");
                Console.ReadKey();
            }
        }
        #region Arguments Commands
        static bool ArgsAreValid(string[] args)
        {
            if (DoesArgumentExist("?", args) || 
                DoesArgumentExist("/?", args) ||
                DoesArgumentExist("/help", args) ||
                DoesArgumentExist("/GetHelp", args) ||
                DoesArgumentExist("-GetHelp", args)
                )
            {
                Console.WriteLine(ArgsHelp);
                return false;
            }
            if (args.Length < 3)
            {
                Console.WriteLine("Invalid Arguments.\n\n" + ArgsHelp);
                return false;
            }
            if (string.IsNullOrEmpty(readStringArgumentValue("-report:", args)))//User didn't supply the path to report design
            {
                Console.WriteLine("Missing report design path. Plese supply -Report information.\n\n" + ArgsHelp);
                return false;
            }
            if (string.IsNullOrEmpty(readStringArgumentValue("-saveas", args))) //User didn't supply the save as location
            {
                Console.WriteLine("Missing report data save as path.Please supply -SaveAs information.\n\n" + ArgsHelp);
                return false;
            }
            return true;
        }
        static bool DoesArgumentExist(string arg, string[] args)
        {
            return GetArgumentIndex(arg, args) >= 0;
        }
        static int GetArgumentIndex(string arg, string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (string.Compare(args[i], arg, true) == 0) return i;
            }
            return -1;
        }
        static int GetArgumentIndexThatsStartsWith(string arg, string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].StartsWith(arg, StringComparison.OrdinalIgnoreCase)) return i;
            }
            return -1;
        }
        static string readStringArgumentValue(string arg, string[] args)
        {
            int argIndex = -1;
            if ((argIndex = GetArgumentIndexThatsStartsWith(arg, args)) >= 0)
            {
                if (args[argIndex].Length > arg.Length)
                {
                    return args[argIndex].Substring(arg.Length);
                }
            }
            return "";
        }
        static int readIntArgumentValue(string arg, string[] args, int defaultValue)
        {
            int value = defaultValue;
            int argIndex = -1;
            if ((argIndex = GetArgumentIndexThatsStartsWith(arg, args)) >= 0)
            {
                string[] values = args[argIndex].Split(':');
                if (values == null || values.Length != 2)
                    return value;
                int parsedValue = -1;
                if (!int.TryParse(values[1], out parsedValue))
                    return value;
                return parsedValue;
            }
            return value;
        }
        #endregion
        #region Auxilury Methods
        static string GetFileExtensionOnly(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";

            string[] FileParts = fileName.Split('.');
            if (FileParts == null || FileParts.Length < 2)
                return "";
            return FileParts[FileParts.Length - 1];
        }
        static string GetFileNameWithoutExtension(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";

            string Extension = GetFileExtensionOnly(fileName);
            return fileName.Replace("." + Extension, "");

        }
        static string GetFileNameWithoutExtension(string fileName,string Extension)
        {
            if (string.IsNullOrEmpty(fileName))
                return "";
            return fileName.Replace("." + Extension, "");
        }
        static string AppendStringToFileName(string fileName, string textToAppend)
        {
            string FileExtension = GetFileExtensionOnly(fileName);
            string FileNameOnly = GetFileNameWithoutExtension(fileName, FileExtension);

            return FileNameOnly + "_" + textToAppend + "." + FileExtension;
        }
        static string GetToolVersion()
        {
            string Version = "";

            try
            {
                Version CurentVersion = Assembly.GetEntryAssembly().GetName().Version;
                Version = CurentVersion.Major.ToString() + "." + CurentVersion.Minor;
            }
            catch
            {
                //No issue if we suppress the expection here
            }
            return Version;
        }
        #endregion
        [System.Runtime.InteropServices.DllImport("kernel32.dll")]
        private static extern bool AllocConsole(); 
    }
}
